package com.declum.naduvar.locking.handler;

/**
 * This class store the information about Client's lock request. There are four
 * fields to lock/renew/release path.
 * 
 * They are ClientName, Operation_Type, LockPath and LockKey(Other than
 * acquiring lock)
 * 
 * @author clement
 * 
 */
public class RequestHeader {
	/**
	 * Stores the Name of the Client who is requesting
	 */
	private String clientName;

	/**
	 * This is required to renew/release the locks
	 */
	private String lockKey;

	/**
	 * Client has to specify the operation what it wants to do. There can be
	 * Lease_Lock, Renew_Lock and Release_Lock
	 */
	private String operationType;

	/**
	 * The path at which the lock is required
	 */
	private String lockPath;

	/**
	 * Returns the Name of the Client
	 * 
	 * @return
	 */
	public String getClientName() {
		return this.clientName;
	}

	/**
	 * Returns the Key of the Request
	 * 
	 * @return
	 */
	public String getLockKey() {
		return this.lockKey;
	}

	/**
	 * Returns the Type of the Command/Request
	 * 
	 * @return
	 */
	public String getOperationType() {
		return this.operationType;
	}

	/**
	 * Returns the Lock path
	 * 
	 * @return
	 */
	public String getLockPath() {
		return this.lockPath;
	}

	/**
	 * It parses the String as key/value pair from "key: value" format. Returns
	 * true of successfully parser, else false.
	 * 
	 * @param data
	 *            string to be parsed
	 * @return
	 */
	public boolean parse(String data) {
		String[] part = data.split("\\s*:\\s*");
		if (part.length == 2) {
			if (part[0].toLowerCase().equals("name")) {
				this.clientName = part[1].trim();
			} else if (part[0].toLowerCase().equals("key")) {
				this.lockKey = part[1].trim();
			} else if (part[0].toLowerCase().equals("path")) {
				this.lockPath = part[1].trim();
			} else if (part[0].toLowerCase().equals("type")) {
				this.operationType = part[1].trim();
			}
			return true;
		} else {
			return false;
		}
	}

	/**
	 * This returns true/false based on the completeness of the header. For now
	 * it'll just returns true if all values are not null. But Key can be null
	 * if the client wants the lock to be created newly.
	 * 
	 * So that implementation is pending
	 * 
	 * For now, the client has to specify the key with some dummy value. In our
	 * case, it just the client name itself
	 * 
	 * @return
	 */
	public boolean isComplete() {
		return ((this.clientName != null) && (this.lockPath != null) && (this.operationType != null))
				&& (this.lockKey != null);
	}
}
